<template>
  <a-breadcrumb class="breadcrumb" v-if="breadcrumbList.length !== 1">
    <a-breadcrumb-item  v-for="(item, index) in breadcrumbList" :key="index">
      <span v-if="index === breadcrumbList.length - 1">
        {{$t(item.meta.title)}}
      </span>
      <a v-else @click.prevent="handleLink(item)">{{$t(item.meta.title)}}</a>
    </a-breadcrumb-item>
  </a-breadcrumb>
</template>

<script>
// import { mapState } from 'vuex'
import * as pathToRegexp from 'path-to-regexp'
export default {
  name: 'Breadcrumb',
  data () {
    return {
      breadcrumbList: null
    }
  },
  watch: {
    $route (route) {
      this.getBreadcrumb()
    }
  },
  created () {
    this.getBreadcrumb()
  },
  methods: {
    getBreadcrumb () {
      let matched = this.$route.matched.filter(item => item.meta && item.meta.title)
      const first = matched[0]
      if (!this.isDashboard(first)) {
        const dashboard = [{ path: '/', meta: { title: 'navigation.home' } }]
        matched = dashboard.concat(matched)
      }
      this.breadcrumbList = matched.filter(item => item.meta && item.meta.title && item.meta.breadcrumb !== false)
    },
    isDashboard (route) {
      const { name } = route
      if (!name) {
        return false
      }
      return name.toLowerCase() === 'dashboard'
    },
    pathCompile (path) {
      // To solve this problem https://github.com/PanJiaChen/vue-element-admin/issues/561
      const { params } = this.$route
      var toPath = pathToRegexp.compile(path)
      return toPath(params)
    },
    handleLink (item) {
      const { redirect, path } = item
      if (redirect) {
        this.$router.push(redirect)
        return
      }
      this.$router.push(this.pathCompile(path))
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '../../styles/var.styl'
.breadcrumb
  background #fff
  // border-top  1px solid borderColor
  float left
  padding 14px 24px 8px
</style>
